package com.ywu.third.exec.standard.exec.param;

import com.ywu.common.gson.GsonUtils;
import com.ywu.third.exec.standard.entity.YwuThirdExecEntity;
import com.ywu.third.exec.standard.entity.YwuThirdExecParamEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ParamParseCoreService
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/10/16 8:46
 * @Version 1.0
 **/
@Service
@Slf4j
public class ParamParseCoreService {

    private Map<String, YwuExecParamParse> ywuExecParamParseMap;

    @Autowired
    private List<YwuExecParamParse> ywuExecParamParse;

    /**
    * @Author GroundDemo
    * @Description 初始化map
    * @Date 8:58 2024/10/16
    * @Param []
    * @return void
    **/
    private void initMap() {
        // 如果当前engineMap不为空的话，表示已初始化
        if (!CollectionUtils.isEmpty(ywuExecParamParseMap)) {
            return;
        }
        ywuExecParamParseMap = new HashMap<>();
        for (YwuExecParamParse paramParse : ywuExecParamParse) {
            String paramType = paramParse.paramType();
            ywuExecParamParseMap.put(paramType, paramParse);
        }
    }

    /**
     * @Author GroundDemo
     * @Description 解析参数信息
     * @Date 16:04 2024/10/14
     * @Param [entity]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    public Map<String, Object> parseThirdExecParam(YwuThirdExecEntity entity) {
        // 初始化map
        initMap();
        // 存储解析后的参数map
        Map<String, Object> map = new LinkedHashMap<>();
        // 将参数数据序列化为对象
        List<YwuThirdExecParamEntity> entityList = GsonUtils.deserializeList(entity.getExecParam(), YwuThirdExecParamEntity.class);
        if (CollectionUtils.isEmpty(entityList)) {
            return map;
        }
        // 根据类型解析数据
        for (YwuThirdExecParamEntity temp : entityList) {
            map.put(temp.getName(), parseParam(temp));
        }
        return map;
    }

    /**
    * @Author GroundDemo
    * @Description 解析参数
    * @Date 8:53 2024/10/16
    * @Param [paramInfo]
    * @return java.lang.Object
    **/
    private Object parseParam(YwuThirdExecParamEntity paramInfo) {
        if (ywuExecParamParseMap.containsKey(paramInfo.getType())) {
            YwuExecParamParse paramParse = ywuExecParamParseMap.get(paramInfo.getType());
            return paramParse.parse(paramInfo);
        } else {
            return null;
        }
    }

}
